// ignore_for_file: avoid_print, non_constant_identifier_names, library_private_types_in_public_api

import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:jverify/jverify.dart';

// -----BEGIN PUBLIC KEY-----
// MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7zboXPMlqPIKQJ9VZl+Ee/H6t
// SiSx7M3Ka520e+alo/Hehrg6bnGVDKmPXQZN2SY+7BP/dSJp/kW8LF5jpGtAoUKV
// ekOhtxpZY1+mAKi2rR1DLAaUnRmcx/OP/DOeU+SrPfpMigHZlG+PZNW0ySIenSSH
// Iqk77YXiT30dZpw8WQIDAQAB
// -----END PUBLIC KEY-----

// -----BEGIN PRIVATE KEY-----
// MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALvNuhc8yWo8gpAn
// 1VmX4R78fq1KJLHszcprnbR75qWj8d6GuDpucZUMqY9dBk3ZJj7sE/91Imn+Rbws
// XmOka0ChQpV6Q6G3GlljX6YAqLatHUMsBpSdGZzH84/8M55T5Ks9+kyKAdmUb49k
// 1bTJIh6dJIciqTvtheJPfR1mnDxZAgMBAAECgYEAhMuay3WjImi5Fb/k355ChAuc
// c2JbAijk9z4TXJzD4dpEW8o9GKwhyngSqZnorEFhBtsd5OPpurMekkl5UNHhN7LT
// XWn86xzwDcXAf52UTDDuRyCinw9EXHRJ4fwl4HtPFKV70dDVVIPwEYq5P99nQo3k
// 9GSlG9MdY2sOMk6hixECQQDiFL2cCTiFeDGaIppgelKt1uHMOmPEmk7qdfRnVWot
// +r/TDwEj3uQqx1Blwnih0/Gc6dsPOjOIIjDyZlEPWdAdAkEA1Kg1vW8tmrtNsGwF
// kK48BEymbCgjbB6yhO3l4fn4gGdU7CggR0nK1IguOzxMkAGMhpDCv+0YDPNFZRnz
// V9cgbQJAJnzrbqXvNmGo6Bmd+HC6pJehZxhFpdGzP50HF5Rl+B/pCjBSvF2UsGew
// GzLJQJuJVXJGdcgtv646cPnUMO3UTQJACaZwed43tZPWXLEqN3yQoKlRzAquQNPL
// yhh5nB2Z10nZIrZXcKS6nZZocquz1b0cQWcET21U8BGCDqp0zoGmqQJAJ5ejNIWe
// QYTYFOzOiGoG8zrhto6QaLewl8uQ17A+KKPPDren1cSdJaS0Ovw6TGRZTbY85X22
// nqcno0iDLXrrqA==
// -----END PRIVATE KEY-----

void main() => runApp(MaterialApp(
      title: "demo",
      theme: ThemeData(primaryColor: Colors.white),
      home: const MyApp(),
    ));

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  /// 统一 key
  final String f_result_key = "result";

  /// 错误码
  final String f_code_key = "code";

  /// 回调的提示信息，统一返回 flutter 为 message
  final String f_msg_key = "message";

  /// 运营商信息
  final String f_opr_key = "operator";

  String _result = "token=";
  var controllerPHone = TextEditingController();

  ///声明
  final Jverify jverify = Jverify();
  String? _token; //认证成功之后返回的token

  @override
  void initState() {
    super.initState();

    ///初始化极光SDK
    initPlatformState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('极光一键登录'),
        ),
        body: _buildContent(),
      ),
    );
  }

  Widget _buildContent() {
    return Center(
      widthFactor: 2,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: const EdgeInsets.all(20),
            color: Colors.brown,
            width: 300,
            height: 100,
            child: Text(_result),
          ),
          Container(
            margin: const EdgeInsets.fromLTRB(40, 5, 40, 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                CustomButton(
                    onPressed: () {
                      isInitSuccess();
                    },
                    title: "初始化状态"),
                const Text("   "),
                CustomButton(
                  onPressed: () {
                    checkVerifyEnable();
                  },
                  title: "网络环境是否支持",
                ),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.fromLTRB(40, 5, 40, 5),
            child: SizedBox(
              width: double.infinity,
              child: CustomButton(
                onPressed: () {
                  getToken();
                },
                title: "获取号码认证 Token",
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.fromLTRB(40, 5, 40, 5),
            child: TextField(
              autofocus: false,
              style: const TextStyle(color: Colors.black),
              decoration: const InputDecoration(
                  hintText: "手机号码", hintStyle: TextStyle(color: Colors.black)),
              controller: controllerPHone,
            ),
          ),
          Container(
            margin: const EdgeInsets.fromLTRB(40, 5, 40, 5),
            child: SizedBox(
              width: double.infinity,
              child: CustomButton(
                onPressed: () {
                  preLogin();
                },
                title: "预取号",
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.fromLTRB(40, 5, 40, 5),
            child: SizedBox(
              width: double.infinity,
              child: CustomButton(
                onPressed: () {
                  loginAuth();
                },
                title: "一键登录",
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.fromLTRB(40, 5, 40, 5),
            child: SizedBox(
              width: double.infinity,
              child: CustomButton(
                onPressed: () {
                  getSMSCode();
                },
                title: "获取验证码",
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// sdk 初始化是否完成
  void isInitSuccess() {
    jverify.isInitSuccess().then((map) {
      bool result = map[f_result_key];
      setState(() {
        if (result) {
          _result = "sdk 初始换成功";
        } else {
          _result = "sdk 初始换失败";
        }
      });
    });
  }

  /// 判断当前网络环境是否可以发起认证
  void checkVerifyEnable() {
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      setState(() {
        if (result) {
          _result = "当前网络环境【支持认证】！";
        } else {
          _result = "当前网络环境【不支持认证】！";
        }
      });
    });
  }

  /// 获取号码认证token
  void getToken() {
    setState(() {
      _showLoading(context);
    });
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      if (result) {
        jverify.getToken().then((map) {
          int code = map[f_code_key]; //code
          _token = map[f_msg_key]; // msg
          String operator = map[f_opr_key]; // 鉴权key
          setState(() {
            _hideLoading();
            _result = "[$code] message = $_token, operator = $operator";
          });
        });
      } else {
        setState(() {
          _hideLoading();
          _result = "[2016],msg = 当前网络环境不支持认证";
        });
      }
    });
  }

  /// 获取短信验证码
  void getSMSCode() {
    setState(() {
      _showLoading(context);
    });
    String phoneNum = controllerPHone.text;
    if (phoneNum.isEmpty) {
      setState(() {
        _hideLoading();
        _result = "[3002],msg = 没有输入手机号码";
      });
      return;
    }
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      if (result) {
        jverify.getSMSCode(phoneNum: phoneNum).then((map) {
          print("获取短信验证码：${map.toString()}");
          int code = map[f_code_key];
          String message = map[f_msg_key];
          setState(() {
            _hideLoading();
            _result = "[$code] message = $message";
          });
        });
      } else {
        setState(() {
          _hideLoading();
          _result = "[3004],msg = 获取短信验证码异常";
        });
      }
    });
  }

  /// 登录预取号
  void preLogin() {
    setState(() {
      _showLoading(context);
    });
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      if (result) {
        jverify.preLogin().then((map) {
          print("预取号接口回调：${map.toString()}");
          int code = map[f_code_key];
          String message = map[f_msg_key];
          setState(() {
            _hideLoading();
            _result = "[$code] message = $message";
          });
        });
      } else {
        setState(() {
          _hideLoading();
          _result = "[2016],msg = 当前网络环境不支持认证";
        });
      }
    });
  }

  void _showLoading(BuildContext context) {
    // LoadingDialog.show(context);
  }

  void _hideLoading() {
    // LoadingDialog.hidden();
  }

  /// SDK 请求授权一键登录
  void loginAuth() {
    setState(() {
      _showLoading(context);
    });
    jverify.checkVerifyEnable().then((map) {
      //map 数据格式
      bool result = map[f_result_key];
      if (result) {
        bool isiOS = Platform.isIOS;

        /// 自定义授权的 UI 界面，以下设置的图片必须添加到资源文件里，
        /// Android项目将图片存放至drawable文件夹下，可使用图片选择器的文件名,例如：btn_login.xml,入参为"btn_login"。
        /// ios项目存放在 Assets.xcassets。
        JVUIConfig uiConfig = JVUIConfig();

        ///背景图片 背景视频
        // uiConfig.authBGGifPath = "main_gif";
        // uiConfig.authBGVideoPath="main_vi";
        // uiConfig.authBGVideoPath =
        //     "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
        // uiConfig.authBGVideoImgPath = "main_v_bg";

        //导航栏
        //uiConfig.navHidden = true;
        // uiConfig.navColor = Colors.white.value;
        // uiConfig.navText = "";
        // uiConfig.navTextColor = Colors.black.value;
        // uiConfig.navReturnImgPath = "return_bg"; //图片必须存在

        uiConfig.logoWidth = 90;
        uiConfig.logoHeight = 90;
        //uiConfig.logoOffsetX = isiOS ? 0 : null;//(screenWidth/2 - uiConfig.logoWidth/2).toInt();
        uiConfig.logoOffsetY = 120;
        uiConfig.logBtnOffsetX = 170;
        uiConfig.logoVerticalLayoutItem = JVIOSLayoutItem.ItemSuper;
        uiConfig.logoHidden = false;
        uiConfig.logoImgPath =
            "logo"; //logo文件放在 android/app/src/main/res/drawable 里，图片必须存在

        ///自动识别出的手机号码样式配置
        uiConfig.numberFieldWidth = 200;
        uiConfig.numberFieldHeight = 40;
        uiConfig.numFieldOffsetY = 240;
        //布局的参照物 比如在 logo下面
        uiConfig.numberVerticalLayoutItem = JVIOSLayoutItem.ItemSuper;
        uiConfig.numberColor = Colors.black.value;
        uiConfig.numberSize = 20;
        uiConfig.numberTextBold = true;

        /// 服务商提示文字 比如 中国联通提供认证服务
        uiConfig.sloganOffsetX = 132;
        uiConfig.sloganOffsetY = 728;
        uiConfig.sloganVerticalLayoutItem = JVIOSLayoutItem.ItemNone;
        uiConfig.sloganTextColor = Colors.green.value;
        uiConfig.sloganTextSize = 12;
//        uiConfig.slogan
        //uiConfig.sloganHidden = 0;

        ///登录按钮
        uiConfig.logBtnWidth = 280;
        uiConfig.logBtnHeight = 48;
        uiConfig.logBtnOffsetY = 290;
        uiConfig.logBtnOffsetX = 55;
        uiConfig.logBtnVerticalLayoutItem = JVIOSLayoutItem.ItemNone;
        uiConfig.logBtnText = "本机号码一键登录";
        uiConfig.logBtnTextSize = 16;
        uiConfig.logBtnTextColor = Colors.white.value;
        uiConfig.logBtnTextBold = true;

        ///背景颜色图片
        // uiConfig.logBtnBackgroundPath = "login_background";

        ///登录按钮的 点击效果
        // uiConfig.loginBtnNormalImage = "login_btn_normal"; //图片必须存在
        // uiConfig.loginBtnPressedImage = "login_btn_press"; //图片必须存在
        // uiConfig.loginBtnUnableImage = "login_btn_unable"; //图片必须存在

        ///隐私协议
        uiConfig.privacyHintToast =
            true; //only android 设置隐私条款不选中时点击登录按钮默认显示toast。

        uiConfig.privacyState = false; //设置默认勾选
        uiConfig.privacyCheckboxSize = 20;

        ///单选框选中状态
        uiConfig.checkedImgPath = "check_image"; //图片必须存在
        uiConfig.uncheckedImgPath = "uncheck_image"; //图片必须存在
        uiConfig.privacyCheckboxInCenter = true;
        uiConfig.privacyOffsetX = 40;
        uiConfig.privacyCheckboxHidden = false; //checkbox 是否隐藏
        uiConfig.isAlertPrivacyVc = true;
        uiConfig.privacyOffsetY = 40;
        uiConfig.privacyVerticalLayoutItem = JVIOSLayoutItem.ItemNone;
        // uiConfig.clauseName = "百度";
        // uiConfig.clauseUrl = "http://www.baidu.com";
        // uiConfig.clauseBaseColor = Colors.black.value;
        // uiConfig.clauseNameTwo = "协议二";
        // uiConfig.clauseUrlTwo = "http://www.hao123.com";
        uiConfig.clauseColor = Colors.blue.value;
        uiConfig.privacyText = ["我已阅读并同意", "并授权xxx使用账号信息(如昵称、头像、收货地址等)"];
        uiConfig.privacyTextSize = 14;
        uiConfig.privacyItem = [
          JVPrivacy("用户协议", "http://www.baidu.com",
              beforeName: "==", afterName: "++", separator: "*"),
          JVPrivacy("隐私政策", "http://www.baidu.com", separator: "*")
        ];
        uiConfig.textVerAlignment = 1;
        //uiConfig.privacyWithBookTitleMark = true;
        //uiConfig.privacyTextCenterGravity = false;
        uiConfig.authStatusBarStyle = JVIOSBarStyle.StatusBarStyleDarkContent;
        uiConfig.privacyStatusBarStyle = JVIOSBarStyle.StatusBarStyleDefault;
        uiConfig.modelTransitionStyle =
            JVIOSUIModalTransitionStyle.CrossDissolve;

        uiConfig.statusBarColorWithNav = true;
        uiConfig.virtualButtonTransparent = true;

        uiConfig.privacyStatusBarColorWithNav = true;
        uiConfig.privacyVirtualButtonTransparent = true;

        uiConfig.needStartAnim = true;
        uiConfig.needCloseAnim = true;
        uiConfig.enterAnim = "activity_slide_enter_bottom";
        uiConfig.exitAnim = "activity_slide_exit_bottom";

        uiConfig.privacyNavColor = Colors.red.value;
        uiConfig.privacyNavTitleTextColor = Colors.blue.value;
        uiConfig.privacyNavTitleTextSize = 16;

        uiConfig.privacyNavTitleTitle = "ios lai le"; //only ios
        uiConfig.privacyNavReturnBtnImage = "back"; //图片必须存在;

        //协议二次弹窗内容设置 -iOS
        // uiConfig.agreementAlertViewTitleTexSize = 18;
        // uiConfig.agreementAlertViewTitleTextColor = Colors.red.value;
        // uiConfig.agreementAlertViewContentTextAlignment =
        //     JVTextAlignmentType.center;
        // uiConfig.agreementAlertViewContentTextFontSize = 16;
        // uiConfig.agreementAlertViewLoginBtnNormalImagePath = "login_btn_normal";
        // uiConfig.agreementAlertViewLoginBtnPressedImagePath = "login_btn_press";
        // uiConfig.agreementAlertViewLoginBtnUnableImagePath = "login_btn_unable";
        // uiConfig.agreementAlertViewLogBtnTextColor = Colors.black.value;
        //
        // //协议二次弹窗内容设置 -Android
        // JVPrivacyCheckDialogConfig privacyCheckDialogConfig =
        //     JVPrivacyCheckDialogConfig();
        // // privacyCheckDialogConfig.width = 250;
        // // privacyCheckDialogConfig.height = 100;
        // privacyCheckDialogConfig.offsetX = 0;
        // privacyCheckDialogConfig.offsetY = 0;
        // privacyCheckDialogConfig.titleTextSize = 22;
        // privacyCheckDialogConfig.gravity = "center";
        // privacyCheckDialogConfig.titleTextColor = Colors.black.value;
        // privacyCheckDialogConfig.contentTextGravity = "left";
        // privacyCheckDialogConfig.contentTextSize = 14;
        // privacyCheckDialogConfig.logBtnImgPath = "login_btn_normal";
        // privacyCheckDialogConfig.logBtnTextColor = Colors.black.value;
        // uiConfig.privacyCheckDialogConfig = privacyCheckDialogConfig;

        uiConfig.setIsPrivacyViewDarkMode = true; //协议页面是否支持暗黑模式

        //弹框模式
        // JVPopViewConfig popViewConfig = JVPopViewConfig();
        // popViewConfig.width = (screenWidth - 100.0).toInt();
        // popViewConfig.height = (screenHeight - 150.0).toInt();

        // uiConfig.popViewConfig = popViewConfig;

        /// 添加自定义的 控件 到授权界面
        List<JVCustomWidget> widgetList = [];

        // const String textWidgetid = "jv_add_custom_text"; // 标识控件 id
        // JVCustomWidget textWidget =
        //     JVCustomWidget(textWidgetid, JVCustomWidgetType.textView);
        // textWidget.title = "新加 text view 控件";
        // textWidget.left = 20;
        // textWidget.top = 360;
        // textWidget.width = 200;
        // textWidget.height = 40;
        // textWidget.backgroundColor = Colors.yellow.value;
        // textWidget.isShowUnderline = true;
        // textWidget.textAlignment = JVTextAlignmentType.center;
        // textWidget.isClickEnable = true;
        //
        // // 添加点击事件监听
        // jverify.addClikWidgetEventListener(textWidgetid, (eventId) {
        //   print("receive listener - click widget event :$eventId");
        //   if (textWidgetid == eventId) {
        //     print("receive listener - 点击【新加 text】");
        //   }
        // });
        // widgetList.add(textWidget);

        //新加三个按钮
        const String phoneLoginWidgetid = "phone-login"; // 标识控件 id
        JVCustomWidget phoneLoginWidge =
            JVCustomWidget(phoneLoginWidgetid, JVCustomWidgetType.button);
        phoneLoginWidge.left = 110;
        phoneLoginWidge.top = 585;
        phoneLoginWidge.width = 38;
        phoneLoginWidge.height = 38;
        phoneLoginWidge.isShowUnderline = false;
        phoneLoginWidge.btnNormalImageName = "phone";
        phoneLoginWidge.btnPressedImageName = "phone";
        jverify.addClikWidgetEventListener(phoneLoginWidgetid, (eventId) {
          if (phoneLoginWidgetid == eventId) {
            print('手机验证码登录');
          }
        });
        widgetList.add(phoneLoginWidge);

        ///
        const String weChatLoginWidgetid = "weChat-login"; // 标识控件 id
        JVCustomWidget weChatLoginWidge =
            JVCustomWidget(weChatLoginWidgetid, JVCustomWidgetType.button);
        weChatLoginWidge.left = 180;
        weChatLoginWidge.top = 585;
        weChatLoginWidge.width = 38;
        weChatLoginWidge.height = 38;
        weChatLoginWidge.isShowUnderline = false;
        weChatLoginWidge.btnNormalImageName = "wechat";
        weChatLoginWidge.btnPressedImageName = "wechat";
        jverify.addClikWidgetEventListener(weChatLoginWidgetid, (eventId) {
          if (weChatLoginWidgetid == eventId) {
            print('微信登录');
          }
        });
        widgetList.add(weChatLoginWidge);

        ///
        const String qqWidgetid = "qq-login"; // 标识控件 id
        JVCustomWidget qqLoginWidge =
            JVCustomWidget(qqWidgetid, JVCustomWidgetType.button);
        qqLoginWidge.left = 250;
        qqLoginWidge.top = 585;
        qqLoginWidge.width = 38;
        qqLoginWidge.height = 38;
        qqLoginWidge.isShowUnderline = false;
        qqLoginWidge.btnNormalImageName = "qq";
        qqLoginWidge.btnPressedImageName = "qq";
        jverify.addClikWidgetEventListener(qqWidgetid, (eventId) {
          if (qqWidgetid == eventId) {
            print('QQ登录');
          }
        });
        widgetList.add(qqLoginWidge);

        /// 步骤 1：调用接口设置 UI
        jverify.setCustomAuthorizationView(true, uiConfig,
            landscapeConfig: uiConfig, widgets: widgetList);

        /// 步骤 2：调用一键登录接口

        /// 方式一：使用同步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
        /// 先，添加 loginAuthSyncApi 接口回调的监听
        jverify.addLoginAuthCallBackListener((event) {
          setState(() {
            _hideLoading();
            _result = "监听获取返回数据：[${event.code}] message = ${event.message}";
          });
          print(
              "通过添加监听，获取到 loginAuthSyncApi 接口返回数据，code=${event.code},message = ${event.message},operator = ${event.operator}");

          ///跳转
          print('跳转到个人中心页面');
        });

        /// 再，执行同步的一键登录接口
        jverify.loginAuthSyncApi(autoDismiss: true);
      } else {
        setState(() {
          _hideLoading();
          _result = "[2016],msg = 当前网络环境不支持认证";
        });

        /* 弹框模式
        JVPopViewConfig popViewConfig = JVPopViewConfig();
        popViewConfig.width = (screenWidth - 100.0).toInt();
        popViewConfig.height = (screenHeight - 150.0).toInt();

        uiConfig.popViewConfig = popViewConfig;
        */

        /*

        /// 方式二：使用异步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
        /// 先，执行异步的一键登录接口
        jverify.loginAuth(true).then((map) {
          /// 再，在回调里获取 loginAuth 接口异步返回数据（如果是通过添加 JVLoginAuthCallBackListener 监听来获取返回数据，则忽略此步骤）
          int code = map[f_code_key];
          String content = map[f_msg_key];
          String operator = map[f_opr_key];
          setState(() {
           _hideLoading();
            _result = "接口异步返回数据：[$code] message = $content";
          });
          print("通过接口异步返回，获取到 loginAuth 接口返回数据，code=$code,message = $content,operator = $operator");
        });

        */
      }
    });
  }

  ///初始化 SDK
  Future<void> initPlatformState() async {
    ///添加监听
    jverify.addSDKSetupCallBackListener((JVSDKSetupEvent event) {
      print("receive sdk setup call back event :${event.toMap()}");
    });

    ///打开调试模式
    jverify.setDebugMode(true);
    jverify.setCollectionAuth(false);

    /// 必须设置 setup  iOS配置
    jverify.setup(

        /// 极光应用平台 appkey
        appKey: "e93fb6d4fc25d7497b380b4f",

        /// 默认就好
        channel: "devloper-default");
    if (!mounted) return;

    /// 授权页面点击事件监听
    jverify.addAuthPageEventListener((JVAuthPageEvent event) {
      print("receive auth page event :${event.toMap()}");
    });
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(StringProperty('f_result_key', f_result_key));
  }
}

/// 封装 按钮
class CustomButton extends StatelessWidget {
  final VoidCallback? onPressed;
  final String? title;

  const CustomButton({super.key, @required this.onPressed, this.title});

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: onPressed,
      style: ButtonStyle(
        foregroundColor: MaterialStateProperty.all(Colors.white),
        overlayColor: MaterialStateProperty.all(const Color(0xff888888)),
        backgroundColor: MaterialStateProperty.all(const Color(0xff585858)),
        padding:
            MaterialStateProperty.all(const EdgeInsets.fromLTRB(10, 5, 10, 5)),
      ),
      child: Text("$title"),
    );
  }
}
